package com.jcli.novel_p;

import java.io.*;
import java.util.Properties;
import java.util.regex.Pattern;

/**
 * 文本关键字替换，
 */
public class TextReplacementWithProperties {
    public static void main(String[] args) throws IOException {
        String inputFilePath = "input.txt";
        String outputFilePath = "output.txt";
        String propertiesFilePath = "src/main/resources/config.properties";
        File file1 = new File(inputFilePath);
        File file2 = new File(outputFilePath);
        if (!file1.exists()||!file2.exists()){
            file1.createNewFile();
            file2.createNewFile();
        }

        InputStream inputStream = new FileInputStream(propertiesFilePath);

        try {

            // 读取Properties文件
            Properties properties = new Properties();
            properties.load(new InputStreamReader(inputStream, "UTF-8"));
            // properties.load(new FileInputStream(propertiesFilePath));
            properties.list(System.out);

            // 读取文本
            StringBuilder textBuilder = new StringBuilder();
            try (BufferedReader reader = new BufferedReader(new FileReader(inputFilePath))) {
                String line;
                while ((line = reader.readLine()) != null) {
                    textBuilder.append(line).append(System.lineSeparator());
                }
            }

            String text = textBuilder.toString();

            // 使用Properties中的映射进行替换
            for (String key : properties.stringPropertyNames()) {
                String value = properties.getProperty(key);
                // text = text.replace(key, value);
                text = text.replaceAll("(?i)" + Pattern.quote(key), value);

            }

            // 保存修改后的文本到output.txt
            try (BufferedWriter writer = new BufferedWriter(new FileWriter(outputFilePath))) {
                writer.write(text);
            }

            System.out.println("文本替换完成并保存到 " + outputFilePath);
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}
